import { Button, Image, Dialog } from '@nutui/nutui-react-taro';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classnames from 'classnames';
import { useEffect, useMemo, useState } from 'react';

import styles from './index.module.scss';
import Protocol from './Protocol';
import { getAuthCode, getPhone } from '@/utils/login';
import { getApiChoiceOutAuthLogin, getApiChoicePersonInfo } from '@/api';
import ImageLogo from '@/assets/logo.svg';
import { Text } from '@/components';
import { StorageKey } from '@/constants/storage';
import { useRequest } from '@/hooks';
import { BasicLayout } from '@/layouts';
import { RouterUtil } from '@/utils';
import { DEFAULT_SHOP_ID } from '@/constants';
import type { ButtonProps } from '@nutui/nutui-react-taro/dist/types/packages/button/button.taro';

const Page = () => {
  const _shopId = Taro.getStorageSync(StorageKey.SHOP_ID) || DEFAULT_SHOP_ID;
  // 是否已阅读协议
  const [hasRead, setHasRead] = useState<boolean>(false);

  useEffect(() => {
    // 初始化调用一次，判断是否需要授权获取手机号
    hasRead && init();
  }, [hasRead]);

  // 获取用户信息
  const { run: fetchUserInfo } = useRequest(getApiChoicePersonInfo, {
    manual: true,
    onSuccess: (res) => {
      if (res) {
        Taro.setStorageSync(StorageKey.USER_INFO, res);
      }
    },
    onError: (error) => {
      console.error('获取用户信息失败', error);
    },
  });

  // 快捷登录
  const { data: userInfo, run: quickLogin } = useRequest(
    getApiChoiceOutAuthLogin,
    {
      manual: true,
      onSuccess: (res) => {
        if (res.token) {
          Taro.setStorageSync(StorageKey.TOKEN, res.token);
          // 确保 token 已写入缓存后再获取用户信息（使用 setTimeout 确保在下一个事件循环执行）
          setTimeout(() => {
            // 登录成功后获取用户信息并存入缓存
            fetchUserInfo();
            handleJump();
          }, 0);
        }
      },
    },
  );

  const init = async () => {
    const code = await getAuthCode();
    quickLogin({ code });
  };

  const handleQuickLogin: ButtonProps['onGetPhoneNumber'] = async (e) => {
    /**
     *  登录,获取手机号
     */
    if (userInfo?.phone) {
      // 有手机号，但没有绑定微信和手机号，跳转到完善信息页面
      RouterUtil.navigateTo('/pages/user/login/complete/index', {
        phone: userInfo.phone,
        openId: userInfo.openId || '',
      });
    } else {
      // 如果手机号没有，就先获取手机号，然后跳转到完善信息页面
      const phone = await getPhone(e.detail.code as string);
      if (phone && userInfo?.openId) {
        RouterUtil.navigateTo('/pages/user/login/complete/index', {
          phone,
          openId: userInfo.openId,
        });
      }
    }
  };

  // 根据是否阅读协议，决定按钮是否可用
  const buttonConfig = useMemo(() => {
    if (!hasRead) {
      return {
        onClick() {
          Dialog.open('auth-dialog', {
            title: '',
            content: (
              <View>
                请先阅读并同意
                <Text.Link to="/pages/user/protocol/privacy/index">
                  《用户隐私协议》
                </Text.Link>
                和
                <Text.Link to="/pages/user/protocol/software/index">
                  《软件许可使用协议》
                </Text.Link>
              </View>
            ),
            confirmText: '同意',
            cancelText: '不同意',
            onConfirm: () => {
              setHasRead(true);
              Dialog.close('auth-dialog');
            },
            onCancel: () => {
              Dialog.close('auth-dialog');
            },
          });

          return;
        },
      };
    } else if (userInfo?.phone) {
      // 已经获取过手机号
      return {
        onClick: handleQuickLogin,
      };
    } else {
      return {
        openType: 'getPhoneNumber' as ButtonProps['openType'],
        onGetPhoneNumber: handleQuickLogin,
      };
    }
  }, [hasRead, userInfo]);

  const handleJump = () => {
    // 检查是否有保存的返回路径
    const returnPath = Taro.getStorageSync(StorageKey.APP_START_REDIRECT_PATH);
    if (returnPath) {
      // 清除保存的路径
      Taro.removeStorageSync(StorageKey.APP_START_REDIRECT_PATH);
      // 返回到之前的页面（使用 navigateBack 关闭当前登录页，返回到详情页）
      Taro.navigateBack();
      return;
    }

    // 没有返回路径，使用默认跳转逻辑
    if (!!_shopId) {
      RouterUtil.switchTab('/pages/home/index/index');
    } else {
      RouterUtil.navigateTo('/pages/my/index/index');
    }
  }

  return (
    <BasicLayout className={styles.container} fill transparent loginTip={false}>
      <View className={styles.content}>
        <View className={styles.brand}>
          <Image
            className={styles.logo}
            src={ImageLogo}
            width="88px"
            height="88px"
          />
          <View className={styles.name}>LOVE纪</View>
        </View>
        <View className={styles.login}>
          <Button
            className={classnames(styles.btn, styles['btn-primary'])}
            type="primary"
            size="xlarge"
            block
            {...(buttonConfig as any)}
          >
            手机号快捷登录
          </Button>
        </View>

        <View className={styles.register}>
          <Text.Link
            className={styles['register-link']}
            onClick={() => {
              handleJump()
            }}
          >
            免登录体验
          </Text.Link>
        </View>

        <Protocol
          className={styles.protocol}
          value={hasRead}
          onChange={(v) => {
            setHasRead(v);
          }}
        />
      </View>
      <Dialog id="auth-dialog" />
    </BasicLayout>
  );
};

export default Page;
